#-- coding:UTF-8 -- 
# TCP语音留言服务器


import os
import sys
import time
import socket
import threading
import django
# python使用django数据库，下面两条语句是必须的
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

from blog.models import UserInfo
from blog.models import MsgInfo
from myAPI.getServerIP import getServerIP


# TCP_PORT = 5761  #AUDIO_PORT = 5761 #语音端口
# BUFFER_SIZE = 1024
TCP_MEDIA_PORT = 6000

TCP_IP = getServerIP() #获取本机ip地址 192.168.31.18
BUFFER_SIZE = 1024*4

PATH_MEDIA_NAME = "media"  #语音文件路径
MEDIA_NAME = ""

class mediaServer():

    def __init__(self):
        self.CLIENTS = []        

    def startServer(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((TCP_IP, TCP_MEDIA_PORT))
            s.listen(10)
            #print("TCP服务器 ip地址、端口: ", TCP_IP, TCP_PORT)
            while True:
                print('%s:%s Socket TCP服务器，等待接收消息数据...'%(TCP_IP, TCP_MEDIA_PORT))
                conn, addr = s.accept()
                for (con,adr) in self.CLIENTS:
                    if addr[0] == adr[0]:
                        self.CLIENTS.remove((con,adr))   
                self.CLIENTS.append((conn, addr)) 
                print("客户：", len(self.CLIENTS), self.CLIENTS)                 
                threading.Thread(target=self.receSave, args=(conn, addr)).start()
                threading.Thread(target=self.sendPerson, args=(conn, addr)).start()
            s.close()
        except socket.error as msg:
            print ('线程错误：%s '%msg) 
            sys.exit()

    def receSave(self, conn, addr):
        data = conn.recv(12) #print ("等待接收命令...",addr, conn)
        if data == b'CMD_SENDFILE':  #命令：通知服务器，客户端准备发送文件
            self.saveMedia(conn)

    def sendPerson(self, conn, addr):    
        with open("media.txt", "r") as f:
            MEDIA_NAME = f.read()
        personIp = MsgInfo.objects.filter(mediaName=MEDIA_NAME).values_list("personIp", flat=True)[0]
        filepath = "%s/%s"%(PATH_MEDIA_NAME, MEDIA_NAME)        
        if personIp == addr[0]:
            time.sleep(5) #等待5秒,是为了等待语音文件保存完成。即：os.path.isfile(filepath))为真！2023.02.03
            self.sendFile(conn, filepath)
        else:
            print("文件名：？", addr[0], personIp == addr[0], os.path.isfile(filepath), filepath)


    def sendFile(self, conn, filename):
        '''
        发送文件内容
        '''
        if os.path.isfile(filename):  # 判断文件存在
            # 发送文件内容
            with open(filename, 'rb') as f:
                data = 1
                while data != b'':
                    data = f.read(1024*4)
                    try:
                        conn.send(data)  # 发送数据
                        print("发送....")
                    except socket.error as msg:
                        print("err: ", str(msg))
                   
        else:  # 文件不存在情况
            print('文件不存在:', filename)  # 发送数据长度
     
    def saveMedia(self, conn):
        '''
        接收上传的语音文件，并将语音文件保存到服务器 .
        '''
        with open("media.txt", "r") as f:
            MEDIA_NAME = f.read()
        if MEDIA_NAME:
            with open("%s/%s"%(PATH_MEDIA_NAME, MEDIA_NAME), "ab") as f :                 
                while True:
                    data = conn.recv(BUFFER_SIZE)
                    #print("data: ", data) 
                    if data == b'':
                        break
                    f.write(data)
            print("保存上传文件: ", MEDIA_NAME) 
        else:
            print("错误：MEDIA_NAME 为空！")     



 

if __name__ == '__main__':
    media_server = mediaServer() #创建新服务器侦听连接
    threading.Thread(target=media_server.startServer).start()